package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.service.ManagerService;
import com.liuzhilin.util.Response;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
/*
* 删除文章
* */
@WebServlet("/managerArticleDelete")
public class ManagerArticleDelete extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置CORS响应头
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        // 从请求体中获取JSON数据
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String json = sb.toString();

        // 解析JSON数据
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, String> data =objectMapper.readValue(json, Map.class);
            String writer =data.get("writer");
            String title =data.get("title");
            String category =data.get("category");
            String adminName = data.get("adminName");
            //删除文章
            boolean success=ManagerService.deleteArticle(writer, title, category);
            if (success) {
                out.print("{\"success\": true}");
                //记录操作日志
                if(adminName!=null){
                    ManagerService.recordOperationLog(adminName, "删除了用户:"+writer+"发布在"+category+" 标题为:"+title+"的文章",writer);
                }
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "请求格式错误");
        }
    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        // 设置CORS响应头
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
